<template>
  <div class="register">
    <el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form">
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="username">
        <el-input 
          v-model="registerForm.username" 
          type="text" 
          size="large" 
          auto-complete="off" 
          placeholder="账号"
        >
          <template #prefix><svg-icon icon-class="email" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          size="large" 
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleRegister"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          size="large" 
          auto-complete="off"
          placeholder="确认密码"
          @keyup.enter="handleRegister"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input size="large" v-model="registerForm.code" auto-complete="off" placeholder="邮箱验证码" style="width: 63%" @keyup.enter="handleRegister">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="register-vcode">
          <el-button type="info" @click="getVCode" size="large" :disabled="sendEmailBtnFlag" plain>{{ sendEmailBtnMsg }}</el-button>
        </div>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleRegister">
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <el-row style="width: 100%;">
          <el-col :span="24" style="text-align: right">
            <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <el-dialog title="发送注册邮件" :before-close="sendMailClose" v-model="sendEmailFlag" width="400px" style="top: 15%" append-to-body>
      <el-form ref="emailRef" :model="emailForm" :rules="emailRules" label-width="80px" @submit.native.prevent>
        <el-row>
          <el-col :span="14">
            <el-form-item label="验证码" size="large" prop="code">
              <el-input v-model="emailForm.code" placeholder="验证码" maxlength="10" @keyup.enter="sendMail"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="register-code">
            <img :src="codeUrl" @click="getCode" class="register-code-img"/>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.prevent="sendMail" size="large">发送注册邮件</el-button>
        <el-button @click="sendMailClose" size="large">取 消</el-button>
      </div>
    </el-dialog>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>{{footer1}}<a href="https://beian.miit.gov.cn" target="_blank">{{footer2}}</a></span>
    </div>
  </div>
</template>

<script setup>
import { ElMessageBox } from "element-plus";
import { getCodeImg, register,sendEmail } from "@/api/login";

const router = useRouter();
const { proxy } = getCurrentInstance();

const registerForm = ref({
  username: "",
  password: "",
  confirmPassword: "",
  code: "",
  uuid: ""
});

const emailForm=ref({
  username: "",
  code: "",
  uuid: ""
});

const equalToPassword = (rule, value, callback) => {
  if (registerForm.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};
const registerRules = ref({
  username: [
    { required: true, trigger: "blur", message: "请输入注册邮箱" },
    { min: 5, max: 50, message: '用户账号长度必须介于 5 和 50 之间', trigger: 'blur' },
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"]
    }
  ],
  password: [
    { required: true, trigger: "blur", message: "请输入您的密码" },
    { min: 6, max: 16, message: '密码必须为6-16位字母、数字或‘@’和‘_’组成', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入您的密码" },
    { required: true, validator: equalToPassword, trigger: "blur" }
  ]
  // code: [
  //   { min: 6, max: 6, message: '邮箱验证码必须是6位数', trigger: 'blur' },
  //   { required: true, trigger: "change", message: "请输入邮箱验证码" }
  // ]
});
const codeRules = [
  { min: 6, max: 6, message: '邮箱验证码必须是6位数', trigger: 'blur' },
  { required: true, trigger: "change", message: "请输入邮箱验证码" }
];
const emailRules = {
  code: [
    { required: true, trigger: "change", message: "请输入验证码" }
  ]
};
const title=import.meta.env.VITE_APP_TITLE
const footer1=import.meta.env.VITE_APP_FOOTER1
const footer2=import.meta.env.VITE_APP_FOOTER2
const codeUrl = ref("");
const loading = ref(false);
const sendEmailBtnMsg = ref("获取验证码");
const sendEmailBtnFlag=ref(false);
const sendEmailBtnTime=ref(0);
const timer=ref(null);
const sendEmailFlag=ref(false);

function handleRegister() {
  registerRules.value.code=codeRules;
  proxy.$refs.registerRef.validate(valid => {
    if (valid) {
      loading.value = true;
      register(registerForm.value).then(res => {
        const username = registerForm.value.username;
        ElMessageBox.alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", "系统提示", {
          dangerouslyUseHTMLString: true,
          type: "success",
        }).then(() => {
          router.push("/login");
        }).catch(() => {});
      }).catch(() => {
        loading.value = false;
        getCode();
      });
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    codeUrl.value = "data:image/gif;base64," + res.data.img;
    emailForm.value.uuid = res.data.uuid;
  });
}

function sendMailClose(){
  sendEmailFlag.value=false;
}

function timers() {
  timer.value = setInterval(() => {
    if (sendEmailBtnTime.value <= 0) {
      sendEmailBtnFlag.value=false;
      sendEmailBtnMsg.value="获取验证码"
      clearInterval(timer.value)
    }else{
      const msg=sendEmailBtnTime.value+"秒后重发";
      sendEmailBtnTime.value=sendEmailBtnTime.value-1;
      sendEmailBtnMsg.value=msg;
    }
  }, 1000)
}

function sendMail(){
  proxy.$refs.emailRef.validate(valid =>{
    if(valid){
      sendEmail(emailForm.value).then(res => {
        sendMailClose();
        proxy.$modal.msgSuccess("邮件发送成功！");
        registerForm.value.uuid=res.data.uuid
        sendEmailBtnFlag.value=true
        sendEmailBtnTime.value=60
        timers()
      }).catch(err => {
        if(err.code===500001){
          sendMailClose();
        } else {
          getCode();
        }
      })
    }
  })
}

function getVCode() {
  proxy.$refs.registerRef.clearValidate("code")
  registerRules.value.code=null;
  emailForm.value.code="";
  proxy.$refs.registerRef.validate(valid => {
    if (valid) {
      sendEmailFlag.value = true;
      getCode();
      emailForm.value.username=registerForm.value.username;
    }else {
      sendEmailFlag.value = false;
    }
  });
}
</script>

<style lang='scss' scoped>
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.webp");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.register-code {
  width: 33%;
  height: 40px;
  padding-left: 20px;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.register-vcode {
  width: 33%;
  height: 38px;
  padding-left: 20px;
}
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.register-code-img {
  height: 38px;
  padding-top: 2px;
}
</style>
